package com.yc.storage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.base.BaseServiceImpl;
import com.yc.exception.Asserts;
import com.yc.service.IRedisService;
import com.yc.storage.dto.FileStorageDto;
import com.yc.storage.entity.FileStorage;
import com.yc.storage.mapper.FileStorageMapper;
import com.yc.storage.service.IFileStorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 文件管理 服务实现类
 * </p>
 *
 * @author bao
 * @since 2022-04-10
 */
@Service
@RequiredArgsConstructor
public class FileStorageServiceImpl extends BaseServiceImpl<FileStorageMapper, FileStorage> implements IFileStorageService {

    private final IRedisService redisService;
    @Value("${qiniu.domain}")
    private String qiniuDomain;

    @Override
    public String create(String path) {
        FileStorageDto fileStorageDto = (FileStorageDto) redisService.get(path);
        if (path.startsWith(qiniuDomain)) {
            return path.replace(qiniuDomain, "");
        }
        if (ObjectUtil.isNull(fileStorageDto)) {
            Asserts.fail("文件上传失败");
        }
        FileStorage fileStorage = new FileStorage();
        BeanUtil.copyProperties(fileStorageDto, fileStorage);
        if (create(fileStorage)) {
            redisService.del(path);
            return fileStorage.getPath();
        }
        return null;
    }

    @Override
    public boolean create(FileStorage fileStorage) {
        return save(fileStorage);
    }

    @Override
    public boolean delete(List<Long> ids) {
        return removeByIds(ids);
    }

    @Override
    public boolean update(FileStorage fileStorage) {
        return updateById(fileStorage);
    }

    @Override
    public FileStorage queryById(Long id) {
        return getById(id);
    }

    @Override
    public List<FileStorage> selectList() {
        QueryWrapper<FileStorage> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(FileStorage::getId);
        return list(wrapper);
    }

    @Override
    public IPage<FileStorage> selectPage(IPage<FileStorage> page) {
        QueryWrapper<FileStorage> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(FileStorage::getId);
        return page(page, wrapper);
    }

}
